package com.example.config;

import com.example.constants.Constants;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class AckListener implements ChannelAwareMessageListener {

    @Override
    @RabbitHandler
    @RabbitListener(queues = Constants.MY_SMS_QUEUE_NAME)
    public void onMessage(Message message, Channel channel) throws Exception {
        System.out.println("message = " + message);
        System.out.println("message.getBody() = " + message.getBody());

        try {
            System.out.println("处理具体的业务逻辑");
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println("睡眠倒计时: " + (10 - i) + " 秒");
            }
            /**
             * 假设出现异常,回复 nack
             */
            //int i = 1/0;


            /**
             * 手动回复:成功
             * long deliveryTag 回执标签
             * boolean multiple 是否批量
             */
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            /**
             * 手动回复:失败
             * boolean requeue 是否重发,队列是否给消费者重发
             */
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
